import React, { useState, useMemo } from 'react';
import { TableData } from '../../KimiChat';
import { Table, Input, Typography, Badge, Empty, Card, Space, Tag } from 'antd';
import { SearchOutlined, BarChartOutlined } from '@ant-design/icons';
import './DataTable.scss';

interface DataTableProps {
    data: TableData[];
    sessionTitle?: string;
}

type SortField = keyof TableData;
type SortDirection = 'asc' | 'desc';

interface SortConfig {
    field: SortField;
    direction: SortDirection;
}

const DataTable: React.FC<DataTableProps> = ({ data, sessionTitle }) => {
    const [sortConfig, setSortConfig] = useState<SortConfig | null>(null);
    const [filterCategory] = useState<string>('all');
    const [filterStatus] = useState<string>('all');
    const [searchTerm, setSearchTerm] = useState<string>('');

    // 获取所有唯一的类别和状态
    const categories = useMemo(() => {
        const categorySet = new Set(data.map(item => item.category));
        return Array.from(categorySet);
    }, [data]);

    const statuses = useMemo(() => {
        const statusSet = new Set(data.map(item => item.status));
        return Array.from(statusSet);
    }, [data]);

    // 过滤和排序数据
    const processedData = useMemo(() => {
        let filtered = data.filter(item => {
            const matchesCategory = filterCategory === 'all' || item.category === filterCategory;
            const matchesStatus = filterStatus === 'all' || item.status === filterStatus;
            const matchesSearch = searchTerm === '' || 
                item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                item.category.toLowerCase().includes(searchTerm.toLowerCase());
            
            return matchesCategory && matchesStatus && matchesSearch;
        });

        if (sortConfig) {
            filtered.sort((a, b) => {
                const aValue = a[sortConfig.field];
                const bValue = b[sortConfig.field];
                
                if (typeof aValue === 'number' && typeof bValue === 'number') {
                    return sortConfig.direction === 'asc' ? aValue - bValue : bValue - aValue;
                }
                
                const aStr = String(aValue).toLowerCase();
                const bStr = String(bValue).toLowerCase();
                
                if (sortConfig.direction === 'asc') {
                    return aStr.localeCompare(bStr);
                } else {
                    return bStr.localeCompare(aStr);
                }
            });
        }

        return filtered;
    }, [data, sortConfig, filterCategory, filterStatus, searchTerm]);

    const getStatusColor = (status: string) => {
        switch (status) {
            case '正常':
                return 'success';
            case '异常':
                return 'error';
            case '警告':
                return 'warning';
            default:
                return 'default';
        }
    };
    
    // 为 Ant Design Table 组件准备列定义
    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            sorter: (a: TableData, b: TableData) => a.name.localeCompare(b.name),
            sortDirections: ['ascend', 'descend'] as const,
            defaultSortOrder: sortConfig?.field === 'name' ? sortConfig.direction === 'asc' ? 'ascend' : 'descend' : undefined,
        },
        {
            title: '数值',
            dataIndex: 'value',
            key: 'value',
            sorter: (a: TableData, b: TableData) => a.value - b.value,
            sortDirections: ['ascend', 'descend'] as const,
            defaultSortOrder: sortConfig?.field === 'value' ? sortConfig.direction === 'asc' ? 'ascend' : 'descend' : undefined,
            render: (value: number) => <Typography.Text strong style={{ color: '#059669' }}>{value.toLocaleString()}</Typography.Text>
        },
        {
            title: '类别',
            dataIndex: 'category',
            key: 'category',
            sorter: (a: TableData, b: TableData) => a.category.localeCompare(b.category),
            sortDirections: ['ascend', 'descend'] as const,
            defaultSortOrder: sortConfig?.field === 'category' ? sortConfig.direction === 'asc' ? 'ascend' : 'descend' : undefined,
            render: (category: string) => <Tag color="blue">{category}</Tag>,
            filters: categories.map(category => ({ text: category, value: category })),
            onFilter: (value: string, record: TableData) => record.category === value,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            sorter: (a: TableData, b: TableData) => a.status.localeCompare(b.status),
            sortDirections: ['ascend', 'descend'] as const,
            defaultSortOrder: sortConfig?.field === 'status' ? sortConfig.direction === 'asc' ? 'ascend' : 'descend' : undefined,
            render: (status: string) => <Badge status={getStatusColor(status) as "success" | "error" | "default" | "processing" | "warning"} text={status} />,
            filters: statuses.map(status => ({ text: status, value: status })),
            onFilter: (value: string, record: TableData) => record.status === value,
        },
        {
            title: '日期',
            dataIndex: 'date',
            key: 'date',
            sorter: (a: TableData, b: TableData) => a.date.localeCompare(b.date),
            sortDirections: ['ascend', 'descend'] as const,
            defaultSortOrder: sortConfig?.field === 'date' ? sortConfig.direction === 'asc' ? 'ascend' : 'descend' : undefined,
        },
    ];

    if (!sessionTitle) {
        return (
            <div className="data-table">
                <Card className="data-table__card">
                    <div className="data-table__header">
                        <Typography.Title level={5} className="data-table__title">数据分析结果</Typography.Title>
                    </div>
                    <div className="data-table__empty">
                        <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description={
                                <>
                                    <Typography.Text strong>请选择一个对话</Typography.Text>
                                    <br />
                                    <Typography.Text type="secondary" className="data-table__empty-tip">
                                        选择左侧对话后，分析结果将在这里显示
                                    </Typography.Text>
                                </>
                            }
                        />
                    </div>
                </Card>
            </div>
        );
    }
    
    if (data.length === 0) {
        return (
            <div className="data-table">
                <Card className="data-table__card">
                    <div className="data-table__header">
                        <Typography.Title level={5} className="data-table__title">{sessionTitle} - 数据分析结果</Typography.Title>
                    </div>
                    <div className="data-table__empty">
                        <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description={
                                <>
                                    <Typography.Text strong>暂无数据</Typography.Text>
                                    <br />
                                    <Typography.Text type="secondary" className="data-table__empty-tip">
                                        发送消息后，分析结果将在这里显示
                                    </Typography.Text>
                                </>
                            }
                        />
                    </div>
                </Card>
            </div>
        );
    }

    return (
        <div className="data-table">
            <Card className="data-table__card">
                <div className="data-table__header">
                    <Space align="center">
                        <BarChartOutlined />
                        <Typography.Title level={5} className="data-table__title" style={{ margin: 0 }}>
                            数据分析结果
                        </Typography.Title>
                        <Tag color="blue">共 {processedData.length} 条数据</Tag>
                    </Space>
                </div>
                
                <div className="data-table__filters">
                    <Input
                        placeholder="搜索数据..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        prefix={<SearchOutlined />}
                        className="data-table__search-input"
                        allowClear
                    />
                </div>
                
                <div className="data-table__content">
                    <Table
                        dataSource={processedData}
                        columns={columns as any}
                        rowKey="id"
                        pagination={{ 
                            pageSize: 10,
                            showSizeChanger: true,
                            showTotal: (total) => `共 ${total} 条数据`
                        }}
                        size="middle"
                        className="data-table__table"
                        onChange={(pagination, filters, sorter) => {
                            // 处理表格排序变化
                            if (Array.isArray(sorter)) return;
                            if (sorter.order) {
                                setSortConfig({
                                    field: sorter.field as SortField,
                                    direction: sorter.order === 'ascend' ? 'asc' : 'desc'
                                });
                            } else {
                                setSortConfig(null);
                            }
                        }}
                    />
                </div>
            </Card>
        </div>
    );
};

export default DataTable;